package com.airspyar;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class Utils {
	public final static int R=6371;
	
	public static Vector3d calculateVector3d(SimpleLocation l1, SimpleLocation l2){
		float dLat=l2.getLat()-l1.getLat();
		int signY=dLat<0 ? -1:1;
		dLat=(float)Math.toRadians(Math.abs(dLat));
		float distY=R*(float)Math.sqrt(2-2*Math.cos(dLat))*signY;
		
		
		float dLong=l2.getLong()-l1.getLong();		
		if(dLong>180)
			dLong-=360;
		else if(dLong<-180)
			dLong+=360;
		
		int signX=dLong<0 ? -1:1;
		dLong=(float)Math.toRadians(Math.abs(dLong));

		
		float modLat1=Math.abs(l1.getLat());
		float modLat2=Math.abs(l2.getLat());
		
		float R2=R*(float)Math.cos(Math.toRadians( modLat1>modLat2?modLat1:modLat2 ));
		float distX=R2*(float)Math.sqrt(2-2*Math.cos(dLong))*signX;
		return new Vector3d(distX, distY, l2.getAltitude()-l1.getAltitude());
	}
	
	public static float calculateAngle(Vector3d v1, Vector3d v2){
		Vector3d v1copy=v1.clone();
		Vector3d v2copy=v2.clone();
		v1copy.normalize();
		v2copy.normalize();
		return (float)Math.acos(v1copy.dotProduct(v2copy));
	}
		
	public static String fetchPage(String source, int connectTimeout, int readTimeout) throws Exception{
		URL url=new URL(source);
		URLConnection connection=url.openConnection();
		connection.setConnectTimeout(connectTimeout);
		connection.setReadTimeout(readTimeout);
		BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
		String line, buffer="";
		while((line=br.readLine())!=null)
			buffer+=line;
		
		br.close();
		return buffer;
	}
}
